//app.js
App({
  onLaunch: function () {
    // 获取用户信息
        wx.getSetting({
        success: res => {
          //console.log(res.authSetting);
            if (res.authSetting['scope.userInfo']) {
              // 已经授权，可以直接调用 getUserInfo 获取头像昵称，不会弹框
             
              wx.getUserInfo({
                  success: res => {
                    //console.log(1212);
                  // 可以将 res 发送给后台解码出 unionId        
                    this.globalData.userInfo = res.userInfo
                    this.globalData.isLoginAuth = true;
                    // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
                    // 所以此处加入 callback 以防止这种情况
                    if (this.userInfoReadyCallback) {
                        this.userInfoReadyCallback(res)
                    }
                  }
              })
            }
            else{
              if (this.settingReadyCallback) {
                this.settingReadyCallback(res)
              }
            }
        }
        })
    },
    //多张图片上传
    uploadimg:function(data){
        var that = this,
        i=data.i ? data.i : 0,//当前上传的哪张图片
        success=data.success ? data.success : 0,//上传成功的个数
        fail=data.fail ? data.fail : 0;//上传失败的个数
        var orderid = data.rid ? data.rid : 0;
        wx.uploadFile({
            url: data.url,
            filePath: data.path[i],
            name: 'image',//这里根据自己的实际情况改
            formData: {//这里是上传图片时一起上传的数据
                uid: wx.getStorageSync('userId'),
                imgtype:data.imgtype,
                orderid: data.rid
            },
            success: (resp) => {
                success++;//图片上传成功，图片上传成功的变量+1
                console.log(resp);
                that.globalData.uploadid.push(resp.data);
            },
            fail: (res) => {
                fail++;//图片上传失败，图片上传失败的变量+1
                console.log('fail:' + i + "fail:" + fail);
            },
            complete: () => {
                //console.log(i);
                i++;//这个图片执行完上传后，开始上传下一张
                if (i == data.path.length) {   //当图片传完时，停止调用          
                    //console.log('执行完毕');
                   // console.log('成功：' + success + " 失败：" + fail);
                } else {//若图片还没有传完，则继续调用函数
                   // console.log(i);
                    data.i = i;
                    data.success = success;
                    data.fail = fail;
                    that.uploadimg(data);
                }

            }
        });
    },
    //微信小程序授权获取用户详细信息
    getfansinfo: function () {
        var that=this;
        var openId = (wx.getStorageSync('openId'))
        if (openId == '') {
            wx.login({
                success: function (res) {
                    //console.log('获取CODE=' + res.code)
                    if (res.code) {
                        wx.getUserInfo({
                            withCredentials: true,
                            success: function (res_user) {
                                //console.log(res_user);
                                wx.request({
                                    //后台接口地址
                                    url: that.globalData.miniproUrl + 'Getopenidbycode',
                                    data: {
                                        code: res.code,
                                        encryptedData: encodeURIComponent(res_user.encryptedData),
                                        iv: res_user.iv,
                                        upid: wx.getStorageSync('upuid') > 0 ? wx.getStorageSync('upuid') : that.globalData.upuid
                                    },
                                    method: 'GET',
                                    header: {
                                        'content-type': 'application/json'
                                    },
                                    success: function (res) {
                                        //console.info(res);
                                        that.globalData.userInfo = res.data.result;
                                        that.globalData.isLoginAuth = true;
                                        var role = res.data.result.role;
                                        var roleidentity=0;
                                        if (role == '教练' || role == '陪练' || role == '技师' || role == '销售员' || role == '汽服员') {
                                          roleidentity = 1;
                                        }
                                        var roleflag = 'fans';
                                        if (role == '教练' || role == '陪练') {
                                          roleflag = 'teacher';
                                        }
                                        if (role == '技师') {
                                          roleflag = 'mechanic';
                                        }
                                        if (role == '销售员') {
                                          roleflag = 'saler';
                                        }
                                        if (role == '汽服员') {
                                          roleflag = 'carsvr';
                                        }
                                        wx.setStorageSync('roleFlag', roleflag);
                                        wx.setStorageSync('roleidentity', roleidentity);
                                        wx.setStorageSync('openId', res.data.result.open_id);
                                        wx.setStorageSync('userId', res.data.result.id);
                                        wx.setStorageSync('session_key', res.data.result.session_key);
                                        wx.redirectTo({
                                          url: '../index/index',
                                        }) 
                                    }
                                })
                            },
                            fail: function () {
                                wx.showModal({
                                    title: '警告通知',
                                    content: '您点击了拒绝授权,将无法正常显示个人信息,点击确定重新获取授权。',
                                    success: function (res) {
                                        if (res.confirm) {
                                            wx.redirectTo({
                                                url: '../wxauth/wxauth',
                                            })
                                        }
                                    }
                                })
                            },
                            complete: function (res) { }
                        })
                    }
                }
            })
        }
    },
    //数据本地存储优化，判断存储有效时间
    expiratTime:function(name){
        var keyname='time_'+name; //name：是数据存储key。keyname：是有效时间存储key
        var timestamp = Date.parse(new Date());
        var expiration = timestamp + 30*60*1000; //缓存30分钟
        var data_expiration = wx.getStorageSync(keyname);
        if (data_expiration) {
            if (timestamp > data_expiration) {
                //wx.clearStorageSync();
                wx.setStorageSync(name, '');//清空原来数据内容
                wx.setStorageSync(keyname, expiration);
                return false;
            }
            else{
                return true;
            }
        } else {
            wx.setStorageSync(keyname, expiration);
            return false;
        }
    },
    saveformid: function (formId, openid, comefrom, requrl){ //获取收集formid
      var that=this;
      wx.request({
        url: requrl,
        data: {
          cf: comefrom,
          formid: formId,
          openid: openid
        }
      })
    },
    chkyynum:function(){
      var listnav = this.globalData.listInfo;
      if (1 == wx.getStorageSync('roleidentity')) {
        var identity = wx.getStorageSync('roleFlag');
        wx.request({
          url: app.globalData.hostUrl + 'member/appointmentForsvrer',
          data: {
            identity: identity,
            uid: wx.getStorageSync('userId')
          },
          methods: 'GET',
          header: {
            "Content-Type": "json"
          },
          success: function (res) {
            if (res.data.result) {
              listnav[1].num = res.data.result.lists.length;
              this.globalData.listInfo = listnav;
            }
          }
        })
      }
    },
    globalData: {
      listInfo: [
        {
          text: '首页',
          imgUrl: 'icon-home',
          bindevent: 'gohome',
          num:0
        },
        {
          text: '预约',
          imgUrl: 'icon-appoment',
          bindevent: 'yuy',
          num: 0
        },
        {
          text: '订单',
          imgUrl: 'icon-order',
          bindevent: 'orders',
          num: 0
        },
        {
          text: '我的',
          imgUrl: 'icon-mys',
          bindevent: 'mys',
          num: 0
        }
      ],  
      userInfo: null,
      isLoginAuth:false,
      uploadid:[],
      upuid:0,
      appid:'wx90cdf7ccb81718b0',
      //定义请求https链接地址
      hostUrl: 'https://mini.uw0752.com/api/',
      miniproUrl: 'https://mini.uw0752.com/api/Minipolicy/'
    }
})